//
//  JCNSSplitView.swift
//  JCTest3
//
//  Created by Chen on 10/10/2022.
//

import Cocoa

class JCNSComboBoxView: JCBaseBottomView {
    
    let styles = ["System", "Dark", "Light"]
    let sizes = ["System", "Large", "Medium", "Small"]
    let names = ["Maxs", "Enges", "Hamming", "Liu", "Chen"]
    var states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware",
                      "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky",
                      "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi",
                      "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico",
                      "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania",
                      "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont",
                      "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"]
    
    private var firstComboView: NSComboBox = NSComboBox()
    private var secondComboView: NSComboBox = NSComboBox()
    private var thirdComboView: NSComboBox = NSComboBox() //
    private var popupButton: NSPopUpButton = NSPopUpButton()
    

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

//        self.setupViewBackgroundColor(color: NSColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0))
        // Drawing code here.
        self.createSubviews()
    }
    
}

extension JCNSComboBoxView {
    
    func createSubviews() {
        
        /*
        open var hasVerticalScroller: Bool
        open var intercellSpacing: NSSize
        open var itemHeight: CGFloat
        open var numberOfVisibleItems: Int
        open var isButtonBordered: Bool
        open func reloadData()
        open func noteNumberOfItemsChanged()
        open var usesDataSource: Bool
        open func scrollItemAtIndexToTop(_ index: Int)
        open func scrollItemAtIndexToVisible(_ index: Int)
        open func selectItem(at index: Int)
        open func deselectItem(at index: Int)
        open var indexOfSelectedItem: Int { get }
        open var numberOfItems: Int { get }
        */
        self.firstComboView.frame = NSRect(x: 100, y: 100, width: 200, height: 30)
        self.addSubview(self.firstComboView)
        // 这个一定要放在代理前面，代理才能生效
        self.firstComboView.usesDataSource = true
        self.firstComboView.delegate = self
        self.firstComboView.dataSource = self
        self.firstComboView.toolTip = "选择风格"
        self.firstComboView.itemHeight = 30.0
        
        self.firstComboView.stringValue = "System"
        self.firstComboView.completes = false
//        self.firstComboView.addItem(withObjectValue: "System")
//        self.firstComboView.addItem(withObjectValue: "Dark")
        self.firstComboView.backgroundColor = .red
        
        self.secondComboView.frame = NSRect(x: 100, y: 200, width: 200, height: 30)
        self.addSubview(self.secondComboView)
        self.secondComboView.usesDataSource = true
        self.secondComboView.delegate = self
        self.secondComboView.dataSource = self
        self.secondComboView.toolTip = "选择大小"
        self.secondComboView.itemHeight = 30.0
        self.secondComboView.hasVerticalScroller = true
        self.secondComboView.stringValue = "System"
        self.secondComboView.intercellSpacing = CGSize(width: 20, height: 30) // 下拉框与显示框之间的距离
        self.secondComboView.numberOfVisibleItems = 2 // 下拉后能看到的item数目，数据源大于这个数时下拉框能滚动
        self.secondComboView.completes = true
        self.secondComboView.scrollItemAtIndexToTop(0)
        self.secondComboView.isEditable = false
        
        self.thirdComboView.frame = NSRect(x: 350, y: 100, width: 200, height: 30)
        self.addSubview(self.thirdComboView)
        self.thirdComboView.usesDataSource = true
        self.thirdComboView.delegate = self
        self.thirdComboView.dataSource = self
        self.thirdComboView.toolTip = "选择名字"
        self.thirdComboView.stringValue = "Chen"
        self.thirdComboView.noteFocusRingMaskChanged()
        
//        let cell = JCCustomBoxCell(textCell: "")
//        self.thirdComboView.cell = cell
        if #available(OSX 11.0, *) {
            self.thirdComboView.controlSize = .large
        } else {
            // Fallback on earlier versions
        }
        
        // NSPopupButton
        let popButton = NSPopUpButton(frame: NSRect(x: 350, y: 200, width: 200, height: 30))
        self.addSubview(popButton)
        self.popupButton = popButton
        
        popButton.addItems(withTitles: ["one", "two", "three"])
        popButton.stringValue = "one"
        popButton.preferredEdge = .maxY
        
        // 设置是否为下拉
//        popButton.pullsDown = true
//        let menu = NSMenu.init(title: "Select")
//        popButton.menu = menu
//        menu.addItem(withTitle: "one", action: #selector(self.oneItemClicked), keyEquivalent: "")
//        menu.addItem(withTitle: "two", action: #selector(self.twoItemClicked), keyEquivalent: "")
        
    }
    
}

extension JCNSComboBoxView {
    
    @objc func oneItemClicked() {
        
    }
    
    @objc func twoItemClicked() {
        
    }
    
    @objc func popupActions() {
        let arrays = self.popupButton.itemTitles
        self.popupButton.stringValue = arrays[self.popupButton.indexOfSelectedItem]
    }
    
}

extension JCNSComboBoxView: NSComboBoxDelegate {
    
    //    optional func comboBoxWillDismiss(_ notification: Notification)
    /* Notifications */
    func comboBoxWillPopUp(_ notification: Notification) {}

    func comboBoxSelectionDidChange(_ notification: Notification) {}

    func comboBoxSelectionIsChanging(_ notification: Notification) {
        self.firstComboView.reloadData()
        self.secondComboView.reloadData()
    }
    
}

extension JCNSComboBoxView: NSComboBoxDataSource {
    
    // 这个设置下拉时上一次被选中的选项的
    func comboBox(_ comboBox: NSComboBox, indexOfItemWithStringValue string: String) -> Int {
        if comboBox.isEqual(self.thirdComboView) {
            var i = 0
           for str in states {
               if str == string{
                   return i
               }
               i += 1
           }
           return -1
        } else {
            return 1
        }

    }
    /* These two methods are required when not using bindings */
    // 下拉框列表上显示的文字
    // 应该只能返回数据，不能返回一个自定义视图
    func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
        // 自定义的视图目前有问题
        if comboBox == self.thirdComboView {
            return(states[index] as AnyObject)
        } else {
            return comboBox == self.firstComboView ? self.styles[index] : self.sizes[index]
        }
        
    }

    // 下拉框中列表的子菜单个数
    func numberOfItems(in comboBox: NSComboBox) -> Int {
        if  comboBox == self.thirdComboView {
            return (states.count)
        } else {
            return comboBox == self.firstComboView ? self.styles.count : self.styles.count
        }
    }
    
    func comboBox(_ comboBox: NSComboBox, completedString string: String) -> String? {
        if comboBox.isEqual(self.thirdComboView) {
            for state in states {
               // substring must have less characters then stings to search
               if string.count < state.count{
                   // only use first part of the strings in the list with length of the search string
                   let statePartialStr = state.lowercased()[state.lowercased().startIndex..<state.lowercased().index(state.lowercased().startIndex, offsetBy: string.count)]
                   if statePartialStr.range(of: string.lowercased()) != nil {
                       print("SubString Match = \(state)")
                       return state
                   }
               }
           }
           return ""
        } else {
            return ""
        }
    }

}

extension JCNSComboBoxView: NSTextFieldDelegate {
    
    func controlTextDidChange(_ obj: Notification) {
        let object = obj.object as! NSComboBox
        object.completes = true
    }
 
}

// MARK: - 自定义NSComboBoxCell
class JCCustomBoxCell: NSComboBoxCell {
    
    func popUpList() {
        guard self.isPopUpWindowVisible() == true else {
            return
        }
        self.performClick(nil)
        self.showsFirstResponder = true
    }
    
    func closePopUpWindow() {
        if self.isPopUpWindowVisible() {
            self.showsFirstResponder = false
        }
    }
    
    func isPopUpWindowVisible() -> Bool {
       return self.showsFirstResponder
    }
    
}
